package com.educate.common.mongo;


import com.educate.common.web.EmptyUtils;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

public class QueryUtils {

    public static void keyWord(Criteria criteria, String keyWord, String... name) {
        if (name != null
                && name.length != 0
                && EmptyUtils.isNotEmpty(keyWord)) {
            Criteria[] keyCriteria = new Criteria[name.length];
            for (int i = 0; i < keyCriteria.length; i++) {
                keyCriteria[i] = Criteria.where(name[i]).regex(keyWord.trim(), "i");
            }
            criteria.orOperator(keyCriteria);
        }
    }

    public static Criteria keyWord(String keyWord, String... name) {
        if (name != null
                && name.length != 0
                && EmptyUtils.isNotEmpty(keyWord)) {
            if (name.length == 1) {
                return Criteria.where(name[0]).regex(keyWord.trim(), "i");
            } else {
                Criteria criteria = new Criteria();
                Criteria[] keyCriteria = new Criteria[name.length];
                for (int i = 0; i < keyCriteria.length; i++) {
                    keyCriteria[i] = Criteria.where(name[i]).regex(keyWord.trim(), "i");
                }
                criteria.orOperator(keyCriteria);
                return criteria;
            }
        }
        return null;
    }

    public static Query query(List<Criteria> andCriteria) {
        Query query = new Query();
        if (andCriteria.size() > 0) {
            Criteria[] result = new Criteria[andCriteria.size()];
            andCriteria.toArray(result);
            query.addCriteria(new Criteria().andOperator(result));
        }
        return query;
    }
}
